package com.ygl.core.nacos.decorator;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import com.ygl.core.listener.register.RegisterListener;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Map;

/**
 * @Author yanggld
 * @Date 2019/12/6-16:49
 * @Description
 * ----自定义服务注册逻辑----
 */
public class NacosServiceRegistryDecorator extends NacosServiceRegistry {

	private ConfigurableEnvironment environment;
	private ConfigurableApplicationContext configurableApplicationContext;

	public NacosServiceRegistryDecorator(NacosDiscoveryProperties nacosDiscoveryProperties, NacosServiceRegistry nacosServiceRegistry, ConfigurableApplicationContext configurableApplicationContext) {
		super(nacosDiscoveryProperties);
		this.environment = configurableApplicationContext.getEnvironment();
		this.configurableApplicationContext = configurableApplicationContext;
	}

	@Override
	public void register(Registration registration) {
		System.out.println("*******************可以自定义服务注册逻辑**************************");
		// 是否开启服务注册的控制：只有符合条件的服务才可以注册
		Boolean registerControlEnabled = environment.getProperty("spring.application.register.control.enabled", Boolean.class, Boolean.TRUE);
		if (registerControlEnabled) {
			Map<String, RegisterListener> registerListenerMap = configurableApplicationContext.getBeansOfType(RegisterListener.class);
			if (registerListenerMap != null) {
				for (Map.Entry<String, RegisterListener> listenerEntry : registerListenerMap.entrySet()) {
					RegisterListener registerListener = listenerEntry.getValue();
					registerListener.onRegister(registration);
				}
			}
		}
		super.register(registration);
	}

	@Override
	public void deregister(Registration registration) {
		super.deregister(registration);
	}

	@Override
	public void close() {
		super.close();
	}

	@Override
	public void setStatus(Registration registration, String status) {
		super.setStatus(registration, status);
	}

	@Override
	public Object getStatus(Registration registration) {
		return super.getStatus(registration);
	}
}
